package com.cloud.note.repository;

import com.cloud.note.model.Note;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface NoteRepository extends JpaRepository<Note, String> {
    Page<Note> findByUserIdAndIsTrashedFalse(String userId, Pageable pageable);

    Page<Note> findByUserIdAndIsStarredTrueAndIsTrashedFalse(String userId, Pageable pageable);

    Page<Note> findByUserIdAndIsArchivedTrueAndIsTrashedFalse(String userId, Pageable pageable);

    Page<Note> findByUserIdAndIsTrashedTrue(String userId, Pageable pageable);

    @Query("SELECT n FROM Note n JOIN n.tags t WHERE n.userId = :userId AND t.id = :tagId AND n.isTrashed = false")
    Page<Note> findByUserIdAndTagId(@Param("userId") String userId, @Param("tagId") String tagId, Pageable pageable);

    @Query("SELECT n FROM Note n WHERE n.userId = :userId AND (LOWER(n.title) LIKE LOWER(CONCAT('%', :keyword, '%')) OR LOWER(n.content) LIKE LOWER(CONCAT('%', :keyword, '%'))) AND n.isTrashed = false")
    Page<Note> searchByKeyword(@Param("userId") String userId, @Param("keyword") String keyword, Pageable pageable);

    Optional<Note> findByIdAndUserId(String id, String userId);

    List<Note> findByIdInAndUserId(List<String> ids, String userId);
}